package com.wxtf.platform.main.employee;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.FormatUtil;

/**
 * <li>Title: EmpJobMobilityAction.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.main.employee</li>
 * <li>Description: 工作调用-表tb_employee_job_mobility</li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li></li>
 * 
 * @author ma_wenping
 * @version 1.0.0.0
 * 
 */
public class EmpJobMobilityAction extends LogicBase implements CommonsCallProvider{
	private static final Log log = LogFactory.getLog(EmpJobMobilityAction.class);

	public EmpJobMobilityAction(String jsonArray){

	}

	@Override
	public Object run() {
		Object msg = "";
		try {
			if("queryPage".equals(this.getMethodName())) {
				msg = this.select(this.getLogicData());
			} else if("save".equals(this.getMethodName())) {
				msg = this.insert(this.getLogicData());
			} else if("update".equals(this.getMethodName())) {

			} else if("queryPage_job".equals(this.getMethodName())) {
				msg = this.select_job(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}

			if(msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")){
				return msg;
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch(Exception e) {
			msg = ConstantInfoHelper.generateErrorJSONString();
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object insert(Object jsonArray) throws Exception {
		UserBean user = (UserBean) this.getRequest().getSession().getAttribute("userBean");
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		
		String tbe_id = jsonObject.getString("tbe_id");
		String original_org_id = jsonObject.getString("original_org_id");//原单位ID
		String current_org_id = jsonObject.getString("current_org_id");//现单位ID
		String current_org_name = jsonObject.getString("current_org_name");//现单位ID
		String tbejm_reason = jsonObject.getString("tbejm_reason");
		String tbejm_type = jsonObject.getString("tbejm_type");
		
		String tbejm_id = AccessDataBaseUtil.getPKUUID();
		String curTime = FormatUtil.getCurentDateTime();
		String userId = user.getUserId();
		
		StringBuffer buff = new StringBuffer();
		StringBuffer buff1 = new StringBuffer();
		StringBuffer buff2 = new StringBuffer();
		if("1".equals(tbejm_type)){//调动
			sql = "select levels from t_department where department_id = ?";
			List<Object> list = AccessDataBaseUtil.query4List(sql, new Object[]{ current_org_id });
			int levels = Integer.valueOf(String.valueOf(list.get(0)));
			if(levels < 2){//根和一级机构不能添加人员
				return "{\"result\":false,\"resultmessage\":\"调用失败\",\"resultrecord\":\"操作失败，该机构下不能调动人员\"}";
			}
			
			buff.append("insert into tb_employee_job_mobility(")
				.append("tbejm_id,org_id,tbe_id,original_org_id,current_org_id,tbejm_reason,")
				.append("tbejm_time,create_by,create_time,last_modify_by,last_modify_time)values(")
				.append("'").append(tbejm_id).append("',")
				.append("'").append(current_org_id).append("',")
				.append("'").append(tbe_id).append("',")
				.append("'").append(original_org_id).append("',")
				.append("'").append(current_org_id).append("',")
				.append("'").append(tbejm_reason).append("',")
				.append("'").append(curTime).append("',")
				.append("'").append(userId).append("',")
				.append("'").append(curTime).append("',")
				.append("'").append(userId).append("',")
				.append("'").append(curTime).append("')");
			
			buff1.append("update tb_employee set org_id='").append(current_org_id).append("',reserve1='").append(current_org_name).append("' where tbe_id='").append(tbe_id).append("'");
			buff2.append("update tb_family_base set org_id='").append(current_org_id).append("' where tbe_id='").append(tbe_id).append("'");
		} else if("2".equals(tbejm_type)){//离职
			buff.append("update tb_family_base set tbfi_valid = '0',org_id='' where tbe_id='").append(tbe_id).append("'");
			buff1.append("update tb_employee set tbe_status='102-3',org_id='',reserve1='' where tbe_id='").append(tbe_id).append("'");
		} else if("3".equals(tbejm_type)){//死亡
			buff.append("update tb_family_base set tbfi_valid = '0',org_id='' where tbe_id='").append(tbe_id).append("'");
			buff1.append("update tb_employee set tbe_status='102-5',org_id='',reserve1='' where tbe_id='").append(tbe_id).append("'");
		}
		
		String[] sqls = { buff.toString(), buff1.toString(),buff2.toString() };
		AccessDataBaseUtil.executeSQLUpdate(sqls);
		return "\"修改成功\"";
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean) this.getRequest().getSession().getAttribute("userBean");
		
		sql = " from tb_employee where  tbe_employment_forms <> '31'";
		JSONArray array = JSONArray.fromObject(jsonArray);
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			String types = jsonObject.getString("types");
			if("init".equals(types)) {// 初始查询
				sql += " and org_id in (" + user.getCurSubOrgId() + ")";
			} else if("serch1".equals(types)) {// 条件查询
				String orgIds = jsonObject.getString("orgIds");// 机构ID串
				String tbe_name = jsonObject.getString("tbe_name");// 姓名
				String tbe_idcard = jsonObject.getString("tbe_idcard");// 身份证

				StringBuffer buff = new StringBuffer();
				if(StringUtils.isNotBlank(orgIds)) {
					buff.append(" and org_id in (").append(user.getCurSubOrgIds(orgIds)).append(")");
				}
				if(StringUtils.isNotBlank(tbe_name)) {
					buff.append(" and tbe_name like '%").append(tbe_name).append("%'");
				}
				if(StringUtils.isNotBlank(tbe_idcard)) {
					buff.append(" and tbe_idcard like '%").append(tbe_idcard).append("%'");
				}
				sql += buff.toString();
			}
		}

		// 排序
		String sortname = this.getRequest().getParameter("sortname");
		String sortorder = this.getRequest().getParameter("sortorder");
		if(sortname != null && sortname != null) {
			sql += " order by " + sortname + " " + sortorder;
		} else {
			sql += " order by tbe_name desc";
		}
		
		String countSql = "select count(*) " + sql;
		String querySql = "select tbe_id,org_id,reserve1,tbe_idcard,tbe_name,tbe_sex,tbe_birthday,tbe_family_phone,tbe_address,tbe_marital_status  " + sql;
		String[] fields_ = {
				"tbe_id", "org_id", "reserve1", "tbe_idcard", "tbe_name", "tbe_sex", "tbe_birthday",
				"tbe_family_phone", "tbe_address", "tbe_marital_status"
		};
		return AccessDataBaseUtil.query4SQLPagging(fields_, countSql, querySql, this.getPage(), this.getPagesize(), null);
	}

	/**
	 * 查询工作调动的详细信息
	 */
	public Object select_job(Object jsonArray) throws Exception {
		JSONArray array = JSONArray.fromObject(jsonArray);
		JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
		String tbe_id = jsonObject.getString("tbe_id");

		sql = " from tb_employee_job_mobility r where r.tbe_id = ?";
		String countSql = "select count(*) " + sql;
		String querySql = "select (select caption from t_department where department_id = r.original_org_id),(select caption from t_department where department_id = r.current_org_id),r.tbejm_reason,r.tbejm_time " + sql + " order by tbejm_time desc";
		String[] fields_jobm = { "old_org", "now_org", "tbejm_reason", "tbejm_time" };
		return AccessDataBaseUtil.query4SQLPagging(fields_jobm, countSql, querySql, this.getPage(), this.getPagesize(), new Object[] { tbe_id });
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}

}
